#!/bin/bash

# current ip
ipaddr=`cat /amax/conf/env-network |grep PUBLIC_IP|awk -F= '{print $2}'`
# date
today=`date +'metricbeat-8.0.0-20%y.%m.%d'`
#docker root dir
dockerroot=`docker info --format '{{json .DockerRootDir}}'|sed 's/"//g'`



# [1] clean  container
docker ps -a |grep Exited|awk '{print "docker rm "$1}'|sh


# [2] clear web log
echo "
################
# clear web log   #
################
"
# [3] from  4.5.2 web log
find /amax/storage/joblog -type f -atime +7 | xargs rm -f
find /amax/storage/web -type f -atime +7 -name '*.log.*' | xargs rm -f


# [4] delete container running log or   'json-file' 
for f in $(find  $dockerroot/containers/*/*-json.log -size +100M);do > $f;done



# [5] clean  web-client container /tmp.4.5.2 no this bug,because 4.5.2 no download floder
webclient=`docker ps |grep k8s_amax-web-client|awk '{print $1}'`
docker exec $webclient sh -c 'rm -rf /tmp/*-*'

# [6] storage /tmp/aimax/ from download file 
storage=`docker ps |grep k8s_amax-storage|awk '{print $1}'`
docker exec $storage sh -c 'rm -rf /tmp/aimax/*-*'

# [7] overlay2 web-client  /var/log/spring log
for f in $(find  $dockerroot/overlay2/*/merged/var/log/ -size +10M -name '*.log.*' -o -size +10M -name '*.log');do > $f;done
for f in $(find  $dockerroot/overlay2/*/diff/var/log/ -size +10M -name '*.log.*' -o -size +10M -name '*.log');do > $f;done


# [8] clean xcat  message 
xcatapp=`docker ps |grep k8s_xcat|awk '{print $1}'`
docker exec $xcatapp sh -c 'echo > /var/log/messages'


# [9] clear es ,save current day
all_metribeat=`curl "$ipaddr:9200/_cat/indices?v"|grep metricbeat|awk '{print $3}'`
echo $all_metribeat
for x in $all_metribeat;do
if [ $x != $today ];then
 echo "clear log "$x
 curl -X DELETE http://$ipaddr:9200/$x
 echo ""
else
 echo "not delete "$today
fi
done

# [10] clean dind 
dind=`docker ps |grep k8s_gateone-dind|awk '{print $1}'`
docker exec $dind sh -c "docker system prune -a -f"


